package cn.taskservice.common.utils.thread;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置,不同场景下选择不同线程池提交任务
 */
@Configuration
public class ThreadPoolConfig {

    private static final int CPU_NUM = Runtime.getRuntime().availableProcessors();

    /**
     * IO 密集型线程池，适合远程 HTTP 接口调用、大屏统计、数据迁移等
     */
    @Bean("ioTaskExecutor")
    public ThreadPoolTaskExecutor ioTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CPU_NUM + 1);
        executor.setMaxPoolSize(CPU_NUM * 2);
        executor.setQueueCapacity(1024);
        executor.setKeepAliveSeconds(180);
        executor.setThreadNamePrefix("io-task-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }

    /**
     * CPU 密集型线程池，适合复杂业务计算、数据处理等
     */
    @Bean("cpuTaskExecutor")
    public ThreadPoolTaskExecutor cpuTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(CPU_NUM);
        executor.setMaxPoolSize(CPU_NUM);
        executor.setQueueCapacity(0); // 或者设置成 10 以下的小队列
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("cpu-task-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy());
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60);
        executor.initialize();
        return executor;
    }
}
